<?php
// Recogemos los datos del formulario
$entryId = $_POST["entryId"];
$name = $_POST["name"];
$comment = $_POST["comment"];
$captcha = $_POST["captcha"];

// Validamos los datos
$errors = array();
if (empty($name)) $errors[] = $content->langmsg["emptyname"];
if (empty($comment)) $errors[] = $content->langmsg["emptycomment"];
if ($captcha != $_SESSION["captcha"]) $errors[] = $content->langmsg["invalidcaptcha"];
if (count($errors)) {
	echo "ko|".implode("<br />", $errors);
	exit;
}

// Subimos la foto
$pictureNewName = "";
if (isset($_FILES["picture"])) {
	$pictureTmpName = $_FILES["picture"]["tmp_name"];
	$pictureName = $_FILES["picture"]["name"];
	if (strlen($pictureName) > 0) {
		$pictureNewName = strtoupper(md5(microtime()))."_".str_replace(" ", "", $pictureName);
		$picturePath = UPLOADS_DIR.$pictureNewName;
		if (file_exists($picturePath)) {
			$errorCode = Utils::generateRandomCode();
			Utils::writeLog("uploads", array($errorCode, "File already exists", "TmpName: $pictureTmpName", "Name: $pictureName", "NewName: $pictureNewName"));
			echo "ko|".$content->langmsg["commentnotadded"]." ".$errorCode;
			exit;
		} else if (!move_uploaded_file($pictureTmpName, $picturePath)) {
			$errorCode = Utils::generateRandomCode();
			Utils::writeLog("uploads", array($errorCode, "Error uploading file", "TmpName: $pictureTmpName", "Name: $pictureName", "NewName: $pictureNewName"));
			echo "ko|".$content->langmsg["commentnotadded"]." ".$errorCode;
			exit;
		}
	}
}

// Insertamos el comentario en la bd
$db = new DBManager();
$db->connect();
$query = "INSERT INTO blogComments (entryId, status, created, author, content, picture) VALUES ('".$entryId."', '0', NOW(), '".$db->escapeString(utf8_decode($name))."', '".$db->escapeString(utf8_decode($comment))."', '".$db->escapeString($pictureNewName)."')";
if (!$db->runQuery($query)) {
	$errorCode = Utils::generateRandomCode();
	Utils::writeLog("mysql", array($errorCode, $db->getErrorDescription()." (".$db->getErrorCode().")", $query));
	echo "ko|".$content->langmsg["commentnotadded"]." ".$errorCode;
	exit;
}

// Todo ha ido bien
echo "ok|".$content->langmsg["commentadded"];
exit;
?>
